<?php
apf_require_class('APF_Controller');
apf_require_class('Tools_OAUrls');
apf_require_class('Bll_Attendance_DailyReport');
abstract class Oa_Attendance_AbstractController extends APF_Controller {

    /**
     * @var APF
     */
    protected $apf = NULL;
    /**
     *
     * @var NHRequest
     */

    protected $params = NULL;

    protected $request = NULL;


    /**
     *用户信息 test
     * **/
    protected $uinfo;
    protected $apply_num=0;
    /**
     *
     * @var APF_Response
     */
    protected $response = NULL;
    public function __construct() {
        parent::__construct();
        $this->apf = APF::get_instance();
        $this->request = $this->apf->get_request();
        $this->response = $this->apf->get_response();

        $this->oa_datatype = $this->apf->get_config('datatype');
        $this->update_session();

        //$_SESSION['user_id'] = 1;
        $this->uinfo = $_SESSION;
        $this->is_logout();
    }

    private function  update_session(){
        $this->session_act();
        if(isset($_SESSION['name']) && $_SESSION['name'] !=''){

            //suid 伪装登陆
            $params = $this->request->get_parameters();
            $ip = $this->request->get_client_ip();
            if(substr($ip, 0,7) == '192.168' || $ip == '127.0.0.1'){
                if(isset($params['suid'])){
                    $this->set_user_info($params['suid']);
                }
            }
            if($ip=='221.133.228.74'){
                if(isset($params['tzw_suid'])){
                    $this->set_user_info($params['tzw_suid']);
                }
            }
            //TODO update session here
            if($_SERVER['REQUEST_URI'] =='/login/' || $_SERVER['REQUEST_URI'] =='/login'){
                $url = "http://".$_SERVER['HTTP_HOST'].'/';
                $this->response->redirect($url,false,false);
            }
            $this->request->set_attribute('userinfo',$_SESSION);
            $this->set_user_permiss_menu();//设置用户权限菜单
        }
        elseif(preg_match('/\/help\//',$_SERVER['REQUEST_URI'])){
        }
        else{
            //未登录跳转到登录页面
            if(!preg_match('/\/login\//',$_SERVER['REQUEST_URI'])){
                $lasturl = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
                $keep = '';
                if($lasturl) {
                    $keep = '?back='.base64_encode($lasturl);
                }
                $url = "http://".$_SERVER['HTTP_HOST'].'/login/'.$keep;
                $this->response->redirect($url,false,false);
            }
        }
    }
    /**
     * 退出登录
     */
    public function is_logout(){
        //TODO 销毁用户信息 跳转到登录页面
        if(isset($_GET['logout'])){
            $this->session_act();
            session_unset();
            session_destroy();
            $apf = APF::get_instance();
            $oauth = APF::get_instance()->get_config('oauth_info');
            if($oauth){
                $logout = $oauth['oauth_url'].'/logout.php?client_id='.$oauth['client_id'].'&client_secret='.$oauth['client_secret'];
                $apf->get_response()->redirect($logout,false,false);
            }else{
                $apf->get_response()->redirect('/login/',false,false);
            }
        }
    }


    public function session_act(){
        //TODO 其他操作
        session_name('anjuke-oa');
        session_start();
    }

    /**
     * 设置用户的权限
     */
    public function set_user_permiss_menu() {
        $result = array();
        //1.登陆用户
        if(isset($_SESSION['user_id'])) {
            $bll_user = $this->init_user();
            $user_code = $_SESSION['code'];
            $default_manage = APF::get_instance()->get_config('oa_manage');
            //获得权限列表
            //验证是否是默认的管理员
            if(in_array($user_code,(array)$default_manage)) {
                //TODO 返回管理员权限
                $bll_role = $this->init_role();
                $result = $bll_role->get_admin_role();
            }else{
                $user_id = $_SESSION['user_id'];
                $result = $bll_user->get_user_permiss_menu($user_id);
            }
        }

        $this->request->set_attribute('oa_permiss',$result);//权限
        $base_domain = APF::get_instance()->get_config('base_domain');
        $is_apply=0;
        foreach($result as $key => $v) {
            if($v['name']=='审批'){
                $is_apply=1;
            }
            $result[$key]['app_route'] = $base_domain.$v['app_route'];
        }
        //所有有权限审批的菜单都显示未审批数字
        if($is_apply){
            apf_require_class('Bll_Attendance_Audit');
            $aduit_bll = new Bll_Attendance_Audit();
            $this->apply_num = $aduit_bll->get_audit_count($_SESSION['user_id']);
            $this->request->set_attribute('apply_num',$this->apply_num);
        }

        $this->request->set_attribute('role_menu',$result);
        if(!in_array($user_code,(array)$default_manage)) {
            $this->check_permiss($bll_user->get_user_permiss_menu($user_id));//检查用户权限
        }
        return true;
    }

    /**
     * 用户页面的访问权限
     * @return boolean
     */
    public function check_permiss($myperssion) {
        $all_permiss = array();
        //获得所有的mappings
        $mappings = APF::get_instance()->get_config('mappings','route');;
        foreach((array)$mappings as $v) {
            foreach($v as $vv) {
                $str = str_replace(array('*','?','$','^'), array(''), $vv);
                $all_permiss[$str] = $str;
            }
        }
        $oa_permiss_config = APF::get_instance()->get_config('oa_permiss');
        $base_domain = APF::get_instance()->get_config('base_domain');
        $nowscript = $_SERVER['REQUEST_URI'];
        $now_param = $_SERVER['QUERY_STRING'];
        if(empty($nowscript) || $nowscript == '/' || $nowscript == '/?'.$now_param) {
            return true;
        }

        //获得我有的权限
        $my_permiss = array();
       foreach ($myperssion as $key => $v) {
           if($v['app_route'] != '/') {
               $my_permiss[] = $v['app_route'];
           }
       }

       if($this->check_uri_in_permission($nowscript,$my_permiss)) {
           return true;
       }else {
           //获取所有权限
            $bll_role = $this->init_role();
            $rs = $all_db_route = $bll_role->get_admin_role();
            foreach($rs as $v) {
                unset($all_permiss[$v['app_route']]);
            }
            if($this->check_uri_in_permission($nowscript,$all_permiss)) {
                return true;
            }
       }
       APF::get_instance()->get_response()->redirect($base_domain);
    }

    private function check_uri_in_permission($nowscript,$my_permiss) {
        $result  = false;
        if(empty($my_permiss)) {
            return $result;
        }
        foreach($my_permiss as $val) {
            $val = str_replace('/', '\/', $val);
            if(preg_match('/'.$val.'/', $nowscript)){
               $result = true;
               break;
            }
        }
        return $result;
    }

    /**
     * 构造用户登陆数据
     */
    public function set_user_info($uid){
        $this->session_act();
        apf_require_class("Bll_Attendance_UserInfo");
        $bll = new Bll_Attendance_UserInfo;
        $users = $bll->get_user_by_ids($uid);
   //     print_r($users);
        if(!empty($users) and  count($users[0])>0){
            $user_info = $users[0];
            $_SESSION['user_id'] = $user_info['user_id'];
            $_SESSION['email'] = $user_info['email'];
            $_SESSION['code'] = $user_info['code'];
            $_SESSION['name'] = $user_info['name'];
            $_SESSION['english_name'] =$user_info['english_name'];
            $_SESSION['department_id'] = $user_info['department_id'];
            $_SESSION['department_name'] = $user_info['department_name'];
            $_SESSION['enter_date'] = $user_info['enter_date'];
            $_SESSION['city_name'] = $user_info['city_name'];
            $_SESSION['user_type'] = $user_info['user_type'];
            $_SESSION['user_type_date'] = $user_info['user_type_date'];

            $role  = $bll->get_user_role($user_info['user_id']);
            $_SESSION['role_id'] = $role[$user_info['user_id']]['role_id'];
            $_SESSION['role_name'] = $role[$user_info['user_id']]['role_name'];
        }
    }
    //取出当年的年假
    public function get_all_annual($uid=0){
        $result = array();
        //$this->uinfo['user_id'] = 113;
        //$this->uinfo['enter_date'] = '2010-01-05';
        //如果用户未登录，返回空数组
        if($uid){
            apf_require_class("Bll_Attendance_UserInfo");
            $bll_info = new Bll_Attendance_UserInfo();
            $tmp_userinfo = $bll_info->get_user_by_ids($uid);
            $userinfo = $tmp_userinfo[0];
        }else{
            $userinfo = $this->uinfo;
        }
        if(empty($userinfo['user_id'])) {
            return $result;
        }
        apf_require_class('Tools_Tools');
        apf_require_class('Bll_Attendance_UserExt');
        apf_require_class('Bll_Attendance_HistoryAnnual');
        $bll = new Bll_Attendance_UserExt();
        $l_bll = new Bll_Attendance_LeaveRecord();
        $h_bll = new Bll_Attendance_HistoryAnnual();
        $history = $h_bll->get_history_annual_data($userinfo['user_id']);
        $annual['all'] = Tools_Tools::get_instance()->annual($userinfo['enter_date']);
        $annual['used'] = $bll->get_used_annual($userinfo['user_id']);
        $annual['left'] = $annual['all'] - $annual['used'];
        $start = date('Y-m-d',mktime(0,0,0,1,0,date('Y')));
        $end = date('Y-m-d',mktime(0,0,0,1,0,date('Y')+1));
        //用户当年请假总数
        $i_2 = date('Y') - 1;
        $i_1 = date('Y');
        $twevle = isset($history[$i_2])?$history[$i_2]:0;
        $evlevent = isset($history[$i_1]) ?$history[$i_1]:0;
        $clear_day = $l_bll->get_annual_by_condition($userinfo['user_id'],$start,$end);
        //推算需要清零的假
        $sys = Tools_Tools::get_instance()->clear_annual_to_zero($userinfo['enter_date'],$start);
        $need = 0;
        //2010年的所有年假
        $ten = Tools_Tools::get_instance()->clear_annual_to_zero($userinfo['enter_date'],'2010-12-31 00:00:00');
        if($sys['oneyear_leave_annual']) {
            $need += $sys['oneyear_leave_annual'];
        }
        if($ten['oneyear_leave_annual']) {
            $need += $ten['oneyear_leave_annual'];
        }
        $need = $need  - $clear_day - $twevle - $evlevent;
        if($need < 0) {
            $need = 0;
        }
        //如计算正确无问题后，改用need的数值
        $annual['need_do'] = 0;
        if($sys['oneyear_leave_annual'] >= $clear_day){
            $annual['need_do'] = $sys['oneyear_leave_annual'] - $clear_day;
        }
        $annual['need_do'] = $annual['need_do'] < 0 ? 0 : $annual['need_do'];
        $annual['need_do'] = $annual['need_do'] < $annual['left'] ? $annual['need_do'] : $annual['left'];

        $annual['clear_date'] = date('Y.m.d',mktime(0,0,0,1,0,date('Y')+1));
        return $annual;
    }

    /**
     * 检测页面请求是否存在POST操作
     *
     * @return boolean
     */
    public function is_post_request() {
        if ('post' == strtolower($_SERVER['REQUEST_METHOD'])) {
            return true;
        }
        return false;
    }

    /**
     * 初始化user bll
     * @return Bll_Login_User
     */
    public function init_user() {
        apf_require_class('Bll_Login_User');
        return new Bll_Login_User();
    }

    /**
     * 初始化role bll
     * @return Bll_Attendance_Role
     */
    public function init_role() {
        apf_require_class('Bll_Attendance_Role');
        return new Bll_Attendance_Role();
    }

    /**
     * 初始化userinfo bll
     * @return Bll_Attendance_UserInfo
     */
    public function init_userinfo() {
        apf_require_class("Bll_Attendance_UserInfo");
        return new Bll_Attendance_UserInfo();
    }

    /**
     * 初始化monthspecialset bll
     * @return Bll_Attendance_MonthSpecialSet
     */
    public function init_month_set() {
        apf_require_class("Bll_Attendance_MonthSpecialSet");
        return new Bll_Attendance_MonthSpecialSet();
    }

    /**
     * 初始化员工日号勤bll
     * @return Bll_Attendance_AccessDayRecord
     */
    public function init_AccessDayRecord() {
        apf_require_class("Bll_Attendance_AccessDayRecord");
        return new Bll_Attendance_AccessDayRecord();
    }


}
